﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace PwManager
{
    public partial class Form1 : Form
    {
        Login _Login;
        public Form1(Login login)
        {
            _Login = login;
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            mainGridView.AutoGenerateColumns = false;
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            DataBind();
        }

        private void mainGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0)
                return;

            var id = Convert.ToInt64(mainGridView.CurrentRow.Cells["ID"].Value);

            if (mainGridView.Columns[e.ColumnIndex].Name == "Edit")
            {
                var box = StrongBoxCore
                    .PagerList(new StrongBox { ID = id })
                    .FirstOrDefault()
                    .ToDencrypt();
                new FormDetail(box, this).Show();


            }

            if (mainGridView.Columns[e.ColumnIndex].Name == "Del")
            {
                if (DialogResult.OK == MessageBox.Show("你确定删除该列？", "提示", MessageBoxButtons.OKCancel))
                {
                    StrongBoxCore.Del(id);
                    DataBind();
                }
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            new FormDetail(this).Show();
        }

        public void DataBind()
        {
            var box = new StrongBox();
            if (!string.IsNullOrWhiteSpace(txtTitle.Text))
                box.Title = txtTitle.Text.Trim();

            var data = StrongBoxCore
                        .PagerList(box)
                        .ToDencrypt()
                        .ToList();
            mainGridView.DataSource = data;
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            _Login.Close();
        }
    }
}
